package top.easycode.app.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestUtil {

    /**
     * @param response
     * @param key
     * @param value
     * @param maxAge
     */
    public static void addCookie(HttpServletResponse response, String key,
                                 String value, int maxAge) {
        Cookie c = new Cookie(key, value);
        // c.setDomain("yufu.cn");
        c.setPath("/");
        c.setMaxAge(maxAge);
//        c.setHttpOnly(true);
        response.addCookie(c);
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cs = request.getCookies();
        if (cs == null) {
            return null;
        }
        for (int i = 0; i < cs.length; i++) {
            if (cs[i].getName().equalsIgnoreCase(name)) {
                return cs[i].getValue().toString();
            }
        }
        return null;
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cs = request.getCookies();
        if (cs == null) {
            return null;
        }
        for (int i = 0; i < cs.length; i++) {
            if (cs[i].getName().equalsIgnoreCase(name)) {
                return cs[i];
            }
        }
        return null;
    }

    /**
     * 清除cookie
     *
     * @param req
     * @param res
     * @param name
     */
    public static void removeCookie(HttpServletRequest req,
                                    HttpServletResponse res, String name) {
        String domain = RequestUtil.getCookieDomain(req);
        if (null != name) {
            Cookie cookie = new Cookie(name, null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            cookie.setDomain(domain);
//            cookie.setHttpOnly(true);
            res.addCookie(cookie);
        }
    }

    /**
     * 清除所有cookie
     *
     * @param req
     * @param res
     */
    public static void clearCookie(HttpServletRequest req,
                                   HttpServletResponse res) {
        String domain = RequestUtil.getCookieDomain(req);
        Cookie[] cookies = req.getCookies();
        for (int i = 0, len = cookies.length; i < len; i++) {
            Cookie cookie = new Cookie(cookies[i].getName(), null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            cookie.setDomain(domain);
//            cookie.setHttpOnly(true);
            res.addCookie(cookie);
        }
    }

    /**
     * 设置cookie=name的有效期 age==0时删除cookie
     *
     * @param request
     * @param response
     * @param name
     * @param age
     */
    public static void setCookieAge(HttpServletRequest request,
                                    HttpServletResponse response, String name, int age) {
        Cookie[] cs = request.getCookies();
        if (cs == null) {
            return;
        }
        for (int i = 0; i < cs.length; i++) {
            if (cs[i].getName().equalsIgnoreCase(name)) {
                cs[i].setMaxAge(age);
                response.addCookie(cs[i]);
                return;
            }
        }
        return;
    }

    /**
     * 设置所有的cookie的有效期 age==0时删除cookie
     *
     * @param request
     * @param response
     * @param age
     */
    public static void setCookieAge(HttpServletRequest request,
                                    HttpServletResponse response, int age) {
        Cookie[] cs = request.getCookies();
        if (cs == null) {
            return;
        }
        for (int i = 0; i < cs.length; i++) {
            cs[i].setMaxAge(age);
            response.addCookie(cs[i]);
        }
        return;
    }

    /***
     * 生成session_id
     *
     * @return
     */
    // public static String generateSessionId() {
    // String key = "";
    // key = String.valueOf(System.currentTimeMillis()) + String.valueOf((int)
    // (Math.random() * 10000));
    // return key + "a";
    // }

    /***
     * 生成用户id的缓存key
     *
     * @author hankai
     *
     * @return
     */
    // public static String generateUserSessionId() {
    // String key = "";
    // key = String.valueOf(System.currentTimeMillis()) + String.valueOf((int)
    // (Math.random() * 10000));
    // return key + "b";
    // }

    //
    // protected Object getSessionValue(HttpServletRequest request, String key,
    // Class c) throws Exception {
    //
    // String sessionId = getCookieValue(request, key);
    //
    // return cache.getSessionValue(sessionId, key, c);
    // }


    /**
     * 格式化中文字符，防止出现乱码
     *
     * @param str
     * @return
     */
    public static String codeToString(String str) {
        String strString = str;
        try {
            byte tempB[] = strString.getBytes("ISO-8859-1");
            strString = new String(tempB);
            return strString;
        } catch (Exception e) {
            return strString;
        }
    }

    /**
     * 获取当前请求的主页路劲 例如： http://admin.yufu.cn/merchantAdmin
     *
     * @param request
     * @return
     */
   /* public static String getHostAdderss(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String url1 = url.delete(
                url.length() - request.getRequestURI().length(), url.length())
                .toString();
        String backUrl = url1 + request.getServletContext().getContextPath();
        return backUrl;
    }*/

    public static String getCookieDomain(HttpServletRequest request) {
        String domain = "";
        String domainHost = request.getServerName();
        try {
            if (StringUtils.isNotEmpty(domainHost)) {
                if (domainHost.equals("localhost")) {
                    domain = domainHost;
                } else {

                    String[] domainS = domainHost.split("\\.");
                    if (domainS.length > 1) {

                        if (StringUtils.isNumeric(domainS[domainS.length - 1])) { // 是否是ip地址
                            domain = domainHost;
                        } else {
                            domain = domainS[domainS.length - 2] + "."
                                    + domainS[domainS.length - 1];
                            if (domain.contains("com.cn")) {
                                domain = domainS[domainS.length - 3] + "."
                                        + domainS[domainS.length - 1];
                            }
                        }
                    } else {
                        domain = domainHost;
                    }
                }
            }
        } catch (Exception e) {
            domain = domainHost;
        }
        return domain;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String addPort(HttpServletRequest request, String path) {
        String insert = "{port}";

        String port = "";
        String host = request.getHeader("host");
        String[] ss = host.split("\\:");
        if (ss.length < 2) {
            port = ":80";
        } else {
            port = ":" + ss[1];
        }

        if (path.indexOf(insert) == -1) {
            return path;
        }

        // log.debug("从request获取到的端口：" + port);
        // System.out.println("从request获取到的端口=" + port);
        String r = "";
        if (StringUtils.isEmpty(port)) {
            r = path.replace(insert, "");
        } else {
            r = path.replace(insert, port);
        }

        return r;
    }
}
